package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.templates.L1ShopItem;
import com.lineage.server.utils.PerformanceTimer;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ShopCnTable {
  private static final Log _log = LogFactory.getLog(ShopCnTable.class);
  
  private static ShopCnTable _instance;
  
  private static final Map<Integer, ArrayList<L1ShopItem>> _shopList = new HashMap<>();
  
  private static final ArrayList<Integer> _CnitemidList = new ArrayList<>();
  
  private static final Map<Integer, Integer> _allCnShopItem = new HashMap<>();
  
  public static final Map<Integer, Integer> _DailyCnItem = new HashMap<>();
  
  public static ShopCnTable get() {
    if (_instance == null)
      _instance = new ShopCnTable(); 
    return _instance;
  }
  
  public void restshopCn() {
    _shopList.clear();
    load();
  }
  
  public void load() {
    PerformanceTimer timer = new PerformanceTimer();
    Connection cn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("SELECT * FROM shop_cn ORDER BY id");
      rs = ps.executeQuery();
      while (rs.next()) {
        int id = rs.getInt("id");
        int npcId = rs.getInt("npc_id");
        int itemId = rs.getInt("item_id");
        String note = rs.getString("note");
        int enchantlevel = rs.getInt("enchant_level");
        if (ItemTable.get().getTemplate(itemId) == null) {
          _log.error("商城贩卖物品资料错误: 没有这个编号的道具:" + itemId + " 对应NPC编号:" + npcId);
          delete(npcId, itemId);
          continue;
        } 
        int dailybuyingCount = rs.getInt("每日限购数量");
        if (dailybuyingCount > 0)
          _DailyCnItem.put(Integer.valueOf(itemId), Integer.valueOf(dailybuyingCount)); 
        int sellingPrice = rs.getInt("selling_price");
        int purchasingPrice = rs.getInt("purchasing_price");
        int packCount = rs.getInt("pack_count");
        if (sellingPrice > 0 || purchasingPrice > 0) {
          L1ShopItem item = new L1ShopItem(id, itemId, sellingPrice, packCount, enchantlevel, 
              dailybuyingCount, purchasingPrice);
          addShopItem(npcId, item);
        } 
        addSellList(itemId, sellingPrice, purchasingPrice, packCount);
        _CnitemidList.add(Integer.valueOf(itemId));
        if (note.contains("=>"))
          continue; 
        updata_name(npcId, itemId);
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs, ps, cn);
    } 
    _log.info("载入商城贩卖物品资料数量: " + _shopList.size() + "(" + timer.get() + "ms)");
  }
  
  private static void addSellList(int itemId, int sellingPrice, int purchasingPrice, int packCount) {
    Integer currentprice = _allCnShopItem.get(new Integer(itemId));
    double value3 = 0.0D;
    if (purchasingPrice > 0) {
      if (packCount > 0) {
        value3 = (sellingPrice / packCount) / 2.0D;
      } else {
        value3 = purchasingPrice;
      } 
    } else if (sellingPrice > 0) {
      if (packCount > 0) {
        value3 = (sellingPrice / packCount) / 2.0D;
      } else {
        value3 = sellingPrice / 2.0D;
      } 
    } 
    if (value3 < 1.0D) {
      if (currentprice != null)
        _allCnShopItem.remove(new Integer(itemId)); 
      return;
    } 
    if (currentprice != null) {
      if (value3 < currentprice.intValue())
        _allCnShopItem.put(new Integer(itemId), new Integer((int)value3)); 
    } else {
      _allCnShopItem.put(new Integer(itemId), new Integer((int)value3));
    } 
  }
  
  public int getPrice(int itemid) {
    int tgprice = 0;
    Integer price = _allCnShopItem.get(new Integer(itemid));
    if (price != null)
      tgprice = price.intValue(); 
    return tgprice;
  }
  
  public ArrayList<Integer> get_cnitemidlist() {
    return _CnitemidList;
  }
  
  private static void updata_name(int npcId, int itemId) {
    Connection cn = null;
    PreparedStatement ps = null;
    String npcname = NpcTable.get().getNpcName(npcId);
    String itemname = ItemTable.get().getTemplate(itemId).getName();
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("UPDATE `shop_cn` SET `note`=? WHERE `npc_id`=? AND `item_id`=?");
      int i = 0;
      ps.setString(++i, String.valueOf(String.valueOf(npcname)) + "=>" + itemname);
      ps.setInt(++i, npcId);
      ps.setInt(++i, itemId);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  private static void delete(int npc_id, int item_id) {
    Connection cn = null;
    PreparedStatement ps = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("DELETE FROM `shop_cn` WHERE `npc_id`=? AND `item_id`=?");
      ps.setInt(1, npc_id);
      ps.setInt(2, item_id);
      ps.execute();
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  private void addShopItem(int npcId, L1ShopItem item) {
    ArrayList<L1ShopItem> list = _shopList.get(new Integer(npcId));
    if (list == null) {
      list = new ArrayList<>();
      list.add(item);
      _shopList.put(Integer.valueOf(npcId), list);
    } else {
      list.add(item);
    } 
  }
  
  public ArrayList<L1ShopItem> get(int npcId) {
    ArrayList<L1ShopItem> list = _shopList.get(new Integer(npcId));
    if (list != null)
      return list; 
    return null;
  }
  
  public L1ShopItem getTemp(int npcId, int id) {
    ArrayList<L1ShopItem> list = _shopList.get(new Integer(npcId));
    if (list != null) {
      Iterator<L1ShopItem> iterator = list.iterator();
      while (iterator.hasNext()) {
        L1ShopItem shopItem = iterator.next();
        if (shopItem.getId() == id)
          return shopItem; 
      } 
    } 
    return null;
  }
  
  public boolean isSelling(int npcId, int itemid) {
    ArrayList<L1ShopItem> list = _shopList.get(new Integer(npcId));
    if (list != null) {
      Iterator<L1ShopItem> iterator = list.iterator();
      while (iterator.hasNext()) {
        L1ShopItem shopItem = iterator.next();
        if (shopItem.getItemId() == itemid)
          return true; 
      } 
    } 
    return false;
  }
}
